package org.baicaixiaozhan.springbootwebdemo1.util;

import io.jsonwebtoken.*;
import org.baicaixiaozhan.springbootwebdemo1.config.JwtConfig;
import org.baicaixiaozhan.springbootwebdemo1.domain.User;

import javax.crypto.SecretKey;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * DESC: JWT 工具类
 *
 * @author baicaixiaozhan
 * @since 2021/1/29
 */
public class JWTUtils {


    /**
     * 构建一个 token
     *
     * @param user
     * @param secretKey
     * @param jwtConfig
     * @return
     */
    public static String generatorToken(User user, SecretKey secretKey, JwtConfig jwtConfig) {
        return jwtConfig.getTokenPrefix() + Jwts.builder()
                .setSubject(user.getUsername())
                .claim("authorities", user.getUserRole().name())
                .setIssuedAt(new Date())
                .setExpiration(DateUtils.convertToDate(LocalDateTime.now().plusMinutes(1)))
                .signWith(secretKey)
                .compact();
    }

    /**
     * token 解析
     *
     * @param token
     * @param secretKey
     * @return
     * @throws JwtException
     */
    public static Claims tokenParser(String token, SecretKey secretKey) throws JwtException {
        // 创建 jwt 解析器
        JwtParser jwtParser = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build();
        // compacting it into its final String form. A signed JWT is called a 'JWS'.
        Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);

        return claimsJws.getBody();
    }

}
